#include "Buffer.h"

Buffer::Buffer()
: data(NULL), offset(0) {
    // empty
}

Buffer::Buffer(char* data)
: data(data), offset(0) {
    // empty
}

Buffer::~Buffer() {
    // empty
}

void Buffer::assign_raw_data(char* data) {
    this->data = data;
}

char Buffer::get_current_char() {
    return this->data[this->offset];
}

char Buffer::get_char() {
    char ch = this->get_current_char();
    this->move_offset(+1);
    return ch;
}

unsigned int Buffer::get_offset() {
    return this->offset;
}

unsigned int Buffer::set_offset(unsigned int offset) {
    unsigned int previous_offset = this->get_offset();
    this->offset = offset;

    return previous_offset;
}

unsigned int Buffer::move_offset(int delta) {
    return this->set_offset(this->get_offset() + delta);
}

void Buffer::put_char(char value) {
    this->data[this->offset] = value;
    this->move_offset(+1);
}

void Buffer::rewind() {
    this->set_offset(0);
}

char* Buffer::_get_offset_pointer() {
    return this->data + this->get_offset();
}

short Buffer::get_short() {
    short value = *(short*)this->_get_offset_pointer();
    this->move_offset(+2);

    return value;
}

void Buffer::put_short(short value) {
    short* short_data = (short*)this->_get_offset_pointer();
    *short_data = value;
    this->move_offset(+2);
}

int Buffer::get_int() {
    int value = *(int*)this->_get_offset_pointer();
    this->move_offset(+4);

    return value;
}

void Buffer::put_int(int value) {
    int* int_data = (int*)this->_get_offset_pointer();
    *int_data = value;
    this->move_offset(+4);
}

string Buffer::get_string() {
    string result;

    char ch;
    while ((ch = this->get_char()) != '\0') {
        result += ch;
    }

    return result;
}

void Buffer::put_string(string value) {
    for (unsigned int i = 0; i < value.length(); i++) {
        this->put_char(value[i]);
    }
    this->put_char('\0');
}
